package cn.wolfcode.interceptor;

import cn.wolfcode.annotion.PermissionAnnotation;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.redis.service.IEmployeeRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeRedisService employeeRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否为映射方法,如果不是直接放行
        if (!(handler instanceof HandlerMethod)){
                return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        PermissionAnnotation ano = method.getMethodAnnotation(PermissionAnnotation.class);
        if (ano == null){
            return true;
        }
        //获取cookie的token
       /* Cookie[] cookies = request.getCookies();*/
        String token = request.getHeader("token");
     /*   if (cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                }
            }
        }*/
        List<Permission> permissions = new ArrayList<>();
        if (StringUtils.hasLength(token)){
            permissions = employeeRedisService.getPermission(token);
        }
        if (permissions.size() > 0){
            for (Permission permission : permissions) {
                if (permission.getExpression().equals(ano.expression())){
                    return true;
                }
            }
        }

        return false;
    }
}
